package org.example;

public class Test4 {
    //leetcode 53 最大子数组和 https://leetcode.cn/problems/maximum-subarray/description/
    public int maxSubArray(int[] nums) {
        int n = nums.length, ret = nums[0];
        int[] dp = new int[n];
        dp[0] = nums[0];
        for (int i = 1; i < n; i++) {
            dp[i] = Math.max(dp[i-1]+nums[i],nums[i]);
            ret = Math.max(ret,dp[i]);
        }
        return ret;
    }

    //优化
    public int maxSubArray1(int[] nums) {
        int n = nums.length, ret = nums[0];
        int prev = nums[0], cur = nums[0];
        for (int i = 1; i < n; i++) {
            cur = Math.max(prev+nums[i],nums[i]);
            prev = cur;
            ret = Math.max(ret,cur);
        }
        return ret;
    }
}
